package com.lechicanh.cgrid.ke.worker;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.lechicanh.cgrid.ke.api.builder.WebUrlBuilder;

public class Worker
{	
	private static final Logger m_logger = Logger.getLogger(WorkerManagement.class.getSimpleName());
	private Long m_page;
	public Worker(Long page){
		m_page = page;
	}
	public List<String> doJob() throws IOException, InterruptedException{
		List<String> list = new LinkedList<String>();
		String fullUrl = WebUrlBuilder.buildUrl(m_page);
		Connection connection = Jsoup.connect(fullUrl);
		if(connection != null) {
			Document doc = null;
			
			while(true){
				try{
					
					doc = connection.get();
					
				}
				catch(SocketTimeoutException e){
					m_logger.info("Error: " + e.getMessage());
					m_logger.info("Try to connect after 20s");
					Thread.sleep(20*1000);
					continue;
				}
				catch(UnknownHostException e){
					m_logger.info("Could not connect to the web page");
					return null;
				}
				break;
			}
			
			for(int i = 0;i <= 99; i++){
				String id;
				 if(i < 10){
                    id = "ctl00_MainContent_ctl0" + i +  "_hypName";
				 }
                 else{
                     id = "ctl00_MainContent_ctl" + i + "_hypName";
                 }
				 Element element = doc.getElementById(id);
				 String keyword = element.text();
				 if(keyword != null){
					 list.add(keyword); 
				 }
			}
		}
		return list;
	}
	
}
